﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Reflection;
using WebMVC.Models;

namespace WebMVC.Helpers
{
    public sealed class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        private PropertyInfo _nameProperty;
        private Type _resourceType;


        public LocalizedDisplayNameAttribute(string displayNameKey)
            : base(displayNameKey)
        {

        }

        public Type NameResourceType
        {
            get
            {
                return _resourceType;
            }
            set
            {
                _resourceType = value;
                _nameProperty = _resourceType.GetProperty(base.DisplayName, BindingFlags.Static | BindingFlags.Public);
            }
        }

        public override string DisplayName
        {
            get
            {
                if (_nameProperty == null)
                {
                    return base.DisplayName;
                }

                return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);
            }
        }

    }

    public class DataLocalizationHelper
    {
        public static string GetLocalizedNameByKey(Culture culture, string keyString, string valuesString)
        {
            var keys = keyString.Split(':');
            int i = 0;
            var langKey = culture.ToString();
            while (!keys[i].Equals(langKey))
            {
                i++;
            }
            int startIndex = Convert.ToInt32(keys[i+1]);
            int length = Convert.ToInt32(keys[i+2]) - startIndex + 1;
            return valuesString.Substring(startIndex, length);
        }
    }
}
